<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {
	public function index(){
		$this->layout->setTitle('User | Manage');
		$page = $this->uri->segment(3) > 1 ? $this->uri->segment(3) : 1;
		$offset = ($page - 1) * PAGE_ITEM;
		if(isset($_GET['s'])){
			$strFind = quotes_to_entities($_GET['s']);
			$filter = " AND user_name LIKE '%". $strFind ."%' OR user_email LIKE '%". $strFind ."%' OR user_sms_code LIKE '%". $strFind ."%'";
			$data['find'] = $strFind;
		}
		$sqlUser = "SELECT SQL_CALC_FOUND_ROWS * FROM tdx_users WHERE 1=1 $filter ORDER BY user_id DESC LIMIT $offset, ".PAGE_ITEM;
		$queryUser = $this->db->query($sqlUser);
		// get total
		$sqlTotal = "SELECT FOUND_ROWS() AS found_row";
		$queryTotal = $this->db->query($sqlTotal);
		$dataTotal = $queryTotal->row();
		if($dataTotal->found_row > 0){
			if($dataTotal->found_row > PAGE_ITEM){
				$this->load->library('pagination');
				$config['base_url'] = $this->config->item('base_url').'/user/index/';
				$config['total_rows'] = $dataTotal->found_row;
				$config['per_page'] = PAGE_ITEM;
				$config['num_tag_open'] = '<li>';
				$config['num_tag_close'] = '</li>';
				$config['cur_tag_open'] = '<li><span>';
				$config['cur_tag_close'] = '</span></li>';
				$config['prev_link'] = 'Previous';
				$config['prev_tag_open'] = '<li>';
				$config['prev_tag_close'] = '</li>';
				$config['next_link'] = 'Next';
				$config['next_tag_open'] = '<li>';
				$config['next_tag_close'] = '</li>';
				$config['uri_segment'] = 3;
				$config['first_tag_open'] = '<li>';
				$config['first_tag_close'] = '</li>';
				$config['last_tag_open'] = '<li>';
				$config['last_tag_close'] = '</li>';
				
				$this->pagination->initialize($config);
				$data['paginate'] = $this->pagination->create_links();
			}
			$data['total'] = $dataTotal->found_row;
			if ($queryUser->num_rows() > 0){
				foreach ($queryUser->result_array() as $row){
					$data['items'][] = $row;
				}
			}
		}
		$this->layout->view(THEME_DIR.'/user_index', $data);
	}
	public function add(){
		$this->layout->setTitle('User | Add new user');
		$this->load->helper(array('string_func', 'string'));
		if(!empty($_POST)){
			if($_POST['username'] == ''){
				$errMsg[] = 'You must enter some data for username field';
			}
			if($_POST['password'] == '' || md5($_POST['password']) != md5($_POST['password2'])){
				$errMsg[] = 'Password does not match';
			}
			if($_POST['email'] == ''){
				$errMsg[] = 'User email is required';
			}
			if($_POST['user_sms_code'] == ''){
				$errMsg[] = 'User SMS code is required';
			}
			
			if(empty($errMsg)){
				// check for existing user
				$sqlCheck = "SELECT user_id FROM tdx_users WHERE user_name='".quotes_to_entities($_POST['username'])."' OR user_email='".quotes_to_entities($_POST['email'])."'";
				$queryCheck = $this->db->query($sqlCheck);
				// check for existing sms code
				$sqlCode = "SELECT user_id FROM tdx_users WHERE user_sms_code='".quotes_to_entities($_POST['user_sms_code'])."'";
				$queryCode = $this->db->query($sqlCode);
				if($queryCheck->num_rows() > 0){
					$errMsg[] = "Username or email already existed.";
				}
				elseif($queryCode->num_rows() > 0){
					$errMsg[] = "SMS code <strong>".quotes_to_entities($_POST['user_sms_code'])."</strong> already existed.";
				}
				else{
					$strSalt = generateSalt();
					$password = generatePassword($_POST['password'], $strSalt);
					$arrData = array(
						'user_name'		=> $_POST['username'],
						'user_email'	=> $_POST['email'],
						'user_password'	=> $password,
						'user_salt'	=> $strSalt,
						'user_sms_code'	=> $_POST['user_sms_code'],
						'user_type'	=> intval($_POST['acctype']),
					);
					if($this->db->insert('tdx_users', $arrData)){
						$data['msg'] = "New user has been added.";
					}
					else{
						$errMsg[] = "An error has been occured when adding new user. Please contact our admin";
					}
				}
			}
			
			if(!empty($errMsg)){
				$data['error'] = true;
				$data['error_msg'] = $errMsg;
			}
		}
		$this->layout->view(THEME_DIR.'/user_add', $data);
	}
	public function edit(){
		$this->layout->setTitle('User | Edit user');
		$this->load->helper(array('string_func', 'string'));
		$uid = intval($this->uri->segment(3));
		$sqlUser = "SELECT * FROM tdx_users WHERE user_id='$uid'";
		$rsUser = $this->db->query($sqlUser);
		if($rsUser->num_rows() > 0){
			$data['userInfo'] = $rsUser->row_array();
			if(!empty($_POST)){
				if($_POST['pwdflag'] == 1){
					if($_POST['password'] == '' || md5($_POST['password']) != md5($_POST['password2'])){
						$errMsg[] = 'Password does not match';
					}
				}
				if($_POST['email'] == ''){
					$errMsg[] = 'User email is required';
				}
				if($_POST['user_sms_code'] == ''){
					$errMsg[] = 'User SMS code is required';
				}
				
				if(empty($errMsg)){
					// check for existing user
					$sqlCheck = "SELECT user_id FROM tdx_users WHERE user_name='".quotes_to_entities($_POST['username'])."' OR user_email='".quotes_to_entities($_POST['email'])."'";
					$queryCheck = $this->db->query($sqlCheck);
					// check for existing sms code
					$sqlCode = "SELECT user_id FROM tdx_users WHERE user_sms_code='".quotes_to_entities($_POST['user_sms_code'])."'";
					$queryCode = $this->db->query($sqlCode);
					if($queryCheck->num_rows() > 1){
						$errMsg[] = "Username or email already existed.";
					}
					elseif($queryCode->num_rows() > 1){
						$errMsg[] = "SMS code <strong>".quotes_to_entities($_POST['user_sms_code'])."</strong> already existed.";
					}
					else{
						$arrData = array(
							'user_email'	=> $_POST['email'],
							'user_sms_code'	=> $_POST['user_sms_code'],
							'user_type'	=> intval($_POST['acctype']),
						);
						if($_POST['pwdflag'] == 1 && $_POST['password'] != ''){
							$strSalt = generateSalt();
							$password = generatePassword($_POST['password'], $strSalt);
							$arrData['user_password'] = $password;
							$arrData['user_salt'] = $strSalt;
						}
						if($this->db->update('tdx_users', $arrData, array("user_id" => $uid))){
							$data['msg'] = "Update successful.";
							$arrData['user_name'] = $data['userInfo']['user_name'];
							$data['userInfo'] = $arrData;
						}
						else{
							$errMsg[] = "An error has been occured when updating user. Please contact our admin";
						}
					}
				}
				
				if(!empty($errMsg)){
					$data['error'] = true;
					$data['error_msg'] = $errMsg;
				}
			}
		}
		else{
			$data['error'] = true;
			$data['error_msg'] = array('User not found');
		}
		$this->layout->view(THEME_DIR.'/user_edit', $data);
	}
	public function login()
	{
		$this->load->helper(array('string_func', 'string', 'url'));
		$result = array();
		if(isset($_POST['username'])){
			$userName = quotes_to_entities($_POST['username']);
			$query = $this->db->query("SELECT user_id, user_name, user_password, user_salt FROM tdx_users WHERE user_name='$userName' AND user_type=1");
			if ($query->num_rows() > 0){
				$row = $query->row_array();
				$password = generatePassword($_POST['password'], $row['user_salt']);
				$sqlPwd = $this->db->query("SELECT user_id, user_name, user_salt, user_email, user_sms_code 
											FROM tdx_users WHERE user_name='".$row['user_name']."' AND user_password='$password' AND user_type=1");
				if ($sqlPwd->num_rows() > 0){
					$userInfo = $sqlPwd->row_array();
					$this->session->set_userdata($userInfo);
					redirect('/home/index', 'location', 301);
				}
				else{
					$result['error'] = true;
					$result['msg'] = "Wrong username or password.";
				}
			}
			
		}
		$this->layout->setLayout('cupcake_login');
		$this->layout->setTitle('User | Login');
		$this->layout->view(THEME_DIR.'/user_login', $result);
	}
	public function logout(){
		$this->load->helper(array('url'));
		$this->session->unset_userdata(array('user_id' => '', 'user_name' => '', 'user_salt' => '', 'user_email' => '', 'user_sms_code' => ''));
		redirect('/user/login', 'location', 301);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */